package com.ceba.test.modules.regist.logicService;

import abc.ID;
import com.ceba.base.config.CommonConfig;
import com.ceba.base.helper.LoggerHelper;
import com.ceba.base.utils.Base64FileUtils;
import com.ceba.base.utils.IDSFileUtils;
import com.ceba.base.web.response.IResult;
import com.ceba.test.base.config.LogicPathUtil;
import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.enums.*;
import com.ceba.test.base.language.ResourceUtils;
import com.ceba.test.base.utils.StringUtil;
import com.ceba.test.base.web.UserUtils;
import com.ceba.test.modules.filemanage.helper.FileUploadDownLoadHelper;
import com.ceba.test.modules.regist.entity.*;
import com.ceba.test.modules.regist.interfaces.LicBase;
import com.ceba.test.modules.regist.service.GenterpriseLicListService;
import com.ceba.test.modules.regist.service.NewEnterpriseRegistService;
import com.ceba.test.modules.regist.service.NewEnterpriseService;

import com.ceba.test.modules.regist.service.NewLicLogService;
import com.ceba.test.modules.regist.utils.LicJsonUtils;
import com.ceba.test.modules.storage.logicService.StorageFileCacheManage;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class NewRegistLogicService {
    private static Logger logger = LoggerFactory.getLogger(NewRegistLogicService.class);
    private FileUploadDownLoadHelper fileUploadDownLoadHelper = new FileUploadDownLoadHelper();
    private NewEnterpriseRegistService newEnterpriseRegistService;

    private NewEnterpriseService newEnterpriseService;
    private LicBase licBase;
    private GenterpriseLicListService genterpriseLicListService;

    private NewLicLogService newLicLogService;

    public String queryEnterpriseRegistLicAll(String key, Map<String,Object> dic,String type)throws Exception {
        String jsonString = newEnterpriseRegistService.queryEnterpriseRegistLicAll(key,dic,type);
        JSONObject o = new JSONObject(jsonString);
        JSONArray arr=new JSONArray();
        if(o.has("rows")) {
            arr = o.getJSONArray("rows");
            if (arr.length() > 0) {
                for (int i = 0; i < arr.length(); i++) {
                    JSONObject jo = arr.getJSONObject(i);
                    if (jo.has("CUSTOMER_GROUP")) {
                        String customerGroup = jo.getString("CUSTOMER_GROUP");
                        if(customerGroup.equals(CustomGroupEnum.ORDIANARY_USER.getCode())){
                            jo.put("CUSTOMER_GROUP",CustomGroupEnum.ORDIANARY_USER.getName());
                        }else if(customerGroup.equals(CustomGroupEnum.FOXCONN_USER.getCode())){
                            jo.put("CUSTOMER_GROUP",CustomGroupEnum.FOXCONN_USER.getName());
                        }
                        String allSignNum = jo.getString("ALL_SIGN_NUM");
                        if(allSignNum!=null){
                            allSignNum = CebaConfig.getDecode(allSignNum);
                            jo.put("ALL_SIGN_NUM",allSignNum);
                        }
                        String systemType = jo.getString("SYSTEM_TYPE");
                        if(systemType!=null){
                            systemType = CebaConfig.getDecode(systemType);
                            jo.put("SYSTEM_TYPE",systemType);
                        }
                        String signedCount = jo.getString("SIGNED_COUNT");
                        if(signedCount!=null){
                            signedCount = CebaConfig.getDecode(signedCount);
                            jo.put("SIGNED_COUNT",signedCount);
                        }

                    }
                }
            }
        }
        return o.toString();
    }


    /**
     *
     * 获取license 对象信息
     *  @param enterpriseId
     * @return
     */
    public EnterpriseRegistLic getLicenseInfo(String filePath ,String enterpriseId,String comName){
//        IResult iResult=new IResult();
//        iResult.setResultCode(ResultStatusEnum.CG.getCode());
         try {
           String  newFilePath =new String( Base64.decodeBase64(filePath));
             LicRequestPar licRequestPar = new LicRequestPar();
             licRequestPar.setLicFilePath(newFilePath);;
             licRequestPar.setEnterpriseId(enterpriseId);
             IResult iResult2=  licBase.deCodeBase64AndASELic(licRequestPar);
             if(iResult2.getResultCode()==ResultStatusEnum.CG.getCode()){
                 EnterpriseRegistLic enterpriseRegistLic=  (EnterpriseRegistLic)iResult2.getData();
                 if(!StringUtil.isEmptyString(comName)){
                     enterpriseRegistLic.setEnterpriseName(CommonConfig.getDecode(comName));
                 }
                 if(!StringUtil.isEmptyString(enterpriseRegistLic.getOnlineWorker())){
                     enterpriseRegistLic.setOnlineWorker(enterpriseRegistLic.getOnlineWorker());
                 }
                 if(enterpriseRegistLic!=null){
                      return  enterpriseRegistLic;
                 }
             }
         } catch (Exception e) {
           LoggerHelper.error(logger, e, ResourceUtils.getMessage("LIC_FILE_READE_COUNT_EXCEPTION"));
         }
    return  null;
    }






    /**
     * 保存/更新 license 记录  客户信息记录  增加license历史记录  导出lic
     * @param registLic
     * @return
     */
    public  IResult addAndExportLicense(EnterpriseRegistLic registLic, IResult iResult,String userId){
        iResult.setResultCode(ResultStatusEnum.CG.getCode());
        boolean licAddSucc=false;
        String licName =ID.getGuid()+".lic";
        String staorId =StorageFileCacheManage.getSystemUseAddressId();
        try {
            //修改客户信息表
            NewEnterprise newEnterprise =  new NewEnterprise();
            newEnterprise.setId(registLic.getFkEnterpiseId());
            newEnterprise.setPcCodes(registLic.getPcCodes());
            newEnterprise.setEnterpriseName(registLic.getEnterpriseName());
            boolean isEnSuss= newEnterpriseService.updateEnterprise(newEnterprise,userId);
            //修改或增加用户license
            EnterpriseRegistLic oleLic=  newEnterpriseRegistService.getEnterpriseRegistLic(registLic.getFkEnterpiseId());

            if(oleLic!=null){
                registLic.setId(oleLic.getId());
                //说明不是第一次导入
                if(!StringUtil.isEmptyString(oleLic.getAllSignNum())){
                    //计算已签名份数 = 总份数-这次添加份数 - 签名剩余份数
                    registLic.setSignedCount(Integer.parseInt(registLic.getAllSignNum()) - Integer.parseInt(registLic.getRemoteNewSignCount()) -  Integer.parseInt(registLic.getAllowSignNum())+"");
                    //计算份数（已签名份数  剩余份数）
                    if(!StringUtil.isEmptyString(registLic.getRemoteNewSignCount())){
                        registLic.setAllSignNum((Integer.parseInt(oleLic.getAllSignNum()))+(Integer.parseInt(registLic.getRemoteNewSignCount()))+"");
                    }else{
                        registLic.setAllSignNum(oleLic.getAllSignNum());
                    }
                    //计算剩余签名份数 = 总份数 - 已签名份数
                    if(!StringUtil.isEmptyString(registLic.getRemoteNewSignCount())){
                        registLic.setAllowSignNum((Integer.parseInt(registLic.getAllSignNum()))- (Integer.parseInt(registLic.getSignedCount()))+"");
                    }else{
                        registLic.setAllowSignNum(oleLic.getAllSignNum());
                    }
                }else{
                    registLic.setAllSignNum(registLic.getRemoteNewSignCount());
                }
                //如果不是正式版，这次是正式版则转正时间是现在
                if(!oleLic.getSystemType().equals(SystemTypeEnum.FORMAL.getType())){
                    if(registLic.getSystemType().equals(SystemTypeEnum.FORMAL.getType()+"")){
                        Date currentTime = new Date();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String dateString = formatter.format(currentTime);
                        registLic.setFormalUseTime(dateString);
                    }
                }
                licAddSucc= newEnterpriseRegistService.updateEnterpriseRegistLic(registLic);
            }else{
                registLic.setId(ID.getGuid());
                if(!StringUtil.isEmptyString(registLic.getRemoteNewSignCount()) ){
                    registLic.setAllSignNum((Integer.parseInt(registLic.getAllowSignNum())+Integer.parseInt(registLic.getRemoteNewSignCount()))+"");
                    registLic.setAllowSignNum((Integer.parseInt(registLic.getAllowSignNum())+Integer.parseInt(registLic.getRemoteNewSignCount()))+"");
                }else{
                    registLic.setAllSignNum(registLic.getAllowSignNum());
                }

                registLic.setSignedCount("0");
                String systemType = registLic.getSystemType();
                //转正时间
                if(systemType.equals(SystemTypeEnum.FORMAL.getType()+"")){
                    Date currentTime = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateString = formatter.format(currentTime);
                    registLic.setFormalUseTime(dateString);
                }
                licAddSucc= newEnterpriseRegistService.addEnterpriseRegistLic(registLic);
            }
            //对lic进行加密 打包
            if(licAddSucc && isEnSuss){
                LicRequestPar par  = new  LicRequestPar();
                String licPath = LogicPathUtil.getPhySicalLicenseFolder( staorId);
                //将内容写入以.lic 结尾的文件
                String outPath =licPath+licName ;
                //将对象转换规定的json格式
                  String json =LicJsonUtils.objectConvertJson(registLic);
                  par.setStrCount(json);
                  par.setEnterpriseId(registLic.getEnterpriseId());
                  par.setLicFilePath(outPath);
                  par.setLicPathDir(licPath);
                IResult iResult2=  licBase.enCodeBase64AndASELic(par);
                  if(iResult2.getResultCode()==ResultStatusEnum.SB.getCode()){
                      iResult.setMessage(ResourceUtils.getMessage("SAVE_EXPORT_LIC_FILE_EXCEPTION"));
                      iResult.setResultCode(ResultStatusEnum.SB.getCode());
                      iResult.setResult(false);
                  }else{
                      //增加表历史表中记录
                      GenterpriseLicList genterpriseLicList = new GenterpriseLicList();
                      genterpriseLicList.setId(ID.getGuid());
                      genterpriseLicList.setLicPath(outPath);
                      genterpriseLicList.setLicName(licName);
                      genterpriseLicList.setEnterpriseLicId(registLic.getId());
                      boolean genIsSucc= genterpriseLicListService.addGenterpriseLicList(genterpriseLicList);
                      if(genIsSucc){
                          addNewLicLog(registLic);
                          iResult.setData(LogicPathUtil.getVirtualPath(staorId,(String)iResult2.get("zipPath")));
                      }else{
                          iResult.setMessage(ResourceUtils.getMessage("SAVE_EXPORT_LIC_FILE_EXCEPTION"));
                          iResult.setResultCode(ResultStatusEnum.SB.getCode());
                          iResult.setResult(false);
                      }
                  }
            }else{
                iResult.setMessage(ResourceUtils.getMessage("SAVE_EXPORT_LIC_FILE_EXCEPTION"));
                iResult.setResultCode(ResultStatusEnum.SB.getCode());
                iResult.setResult(false);
            }

        } catch (Exception e) {
            iResult.setResult(false);
            iResult.setResultCode(ResultStatusEnum.SB.getCode());
            iResult.setMessage(ResourceUtils.getMessage("SAVE_EXPORT_LIC_FILE_EXCEPTION"));
            LoggerHelper.error(logger, e, ResourceUtils.getMessage("SAVE_EXPORT_LIC_FILE_EXCEPTION"));
        }
        return  iResult;

    }

    private boolean addNewLicLog(EnterpriseRegistLic registLic) throws Exception{
        NewLicLog newLicLog = new NewLicLog();
        newLicLog.setEnterpriseId(registLic.getFkEnterpiseId());
        newLicLog.setAvailbaleDate(registLic.getAllowLoginDate().replace("/","-"));
        newLicLog.setAllSignNum(registLic.getAllSignNum());
        newLicLog.setSubordianteService(registLic.getOnlineWorker());
        String shcaKeyFlag = BeKyeEnum.queryNameByCode(registLic.getBeKeyFlag());
        newLicLog.setKeyMode(shcaKeyFlag);
        newLicLog.setCreatePdfMode(registLic.getPdfCreateMode());
        newLicLog.setCertificateExpiryTime(registLic.getSignValidity().replace("/","-"));
        return newLicLogService.add(newLicLog);
    }


    /**
     *
     *直接导出
     * @param fkEnterpiseId/
     * @param
     */

    public  IResult exportLicense( String fkEnterpiseId,IResult iResult) {
        iResult.setResultCode(ResultStatusEnum.CG.getCode());
        String staorId =StorageFileCacheManage.getSystemUseAddressId();
        String licName =ID.getGuid()+".lic";
        try {
            String licPath = LogicPathUtil.getPhySicalLicenseFolder( staorId);
            //将内容写入以.lic 结尾的文件
            String outPath =licPath+licName ;
            //获取license
            EnterpriseRegistLic license=  newEnterpriseRegistService.getEnterpriseRegistLic(fkEnterpiseId);
            NewEnterprise newEnterprise= newEnterpriseService.getNewEnterprise(fkEnterpiseId);
            if(license!=null){
                license.setEnterpriseName(newEnterprise.getEnterpriseName());
                license.setPcCodes(newEnterprise.getPcCodes());
                license.setEnterpriseId(newEnterprise.getEnterpriseId());
                //将对象转换规定的json格式
                LicRequestPar par  = new  LicRequestPar();
                String json =LicJsonUtils.objectConvertJson(license);
                par.setStrCount(json);
                par.setEnterpriseId(license.getEnterpriseId());
                par.setLicFilePath(outPath);
                par.setLicPathDir(licPath);
                IResult iResult2=  licBase.enCodeBase64AndASELic(par);
                if(iResult2.getResultCode()==ResultStatusEnum.CG.getCode()){
                    iResult.setData(LogicPathUtil.getVirtualPath(staorId,(String)iResult2.get("zipPath")));
                }else{
                    iResult.setMessage(ResourceUtils.getMessage("LIC_FILE_READE_COUNT_EXCEPTION"));
                    iResult.setResultCode(ResultStatusEnum.SB.getCode());
                    iResult.setResult(false);
                }

            }else {
                iResult.setResult(false);
                iResult.setResultCode(ResultStatusEnum.SB.getCode());
                iResult.setMessage(ResourceUtils.getMessage("NO_LICENSE_FILE"));
            }

        } catch (Exception e) {
            iResult.setResult(false);
            iResult.setResultCode(ResultStatusEnum.SB.getCode());
            iResult.setMessage(ResourceUtils.getMessage("SAVE_EXPORT_LIC_FILE_EXCEPTION"));
            LoggerHelper.error(logger, e, ResourceUtils.getMessage("SAVE_EXPORT_LIC_FILE_EXCEPTION"));
        }
        return  iResult;

    }









    public IResult uploadLic(HttpServletRequest request, IResult result){
        try {
            //确定上传路径
            String licFileDir = LogicPathUtil.getPhySicalLicenseFolder(StorageFileCacheManage.getSystemUseAddressId());
            //如何文件夹 不存在  即创建
            IDSFileUtils.createDir(licFileDir);
            fileUploadDownLoadHelper.springUpload(licFileDir,"",request,result);
            if(result.get("fileName")!=null){
                if(!StringUtil.isEmptyString((String)result.get("fileName"))){
                    licFileDir+=(String)result.get("fileName");
                    result.setData(Base64.encodeBase64String(licFileDir.getBytes()));
                }
            }
        } catch (Exception e) {
            LoggerHelper.error(logger, e, ResourceUtils.getMessage("UPLOUD_EXPORT_LIC_FILE_EXCEPTION="));
        }
        return  result;
    }




    public IResult licCountInfo(String licFilePath, IResult result,String compId ){
        try {
                  LicRequestPar par = new LicRequestPar();
                    par.setLicFilePath(licFilePath);
                    IResult results= licBase.deCodeBase64Lic(par);
                    //转换成功
                    if(results.getResult()){
                        EnterpriseRegistLic lic=  (EnterpriseRegistLic)results.getData();
                        lic.setFkEnterpiseId(compId);
                        //获取公司信息
                        NewEnterprise newEnterprise =  newEnterpriseService.getNewEnterprise(compId);
                        if(newEnterprise!=null){
                            lic.setEnterpriseName(newEnterprise.getEnterpriseName());
                            lic.setEnterpriseId(newEnterprise.getEnterpriseId());//客户唯一编码
                        }
                        result.setData(results.getData());
                        result.setResult(true);
                        result.setResultCode(ResultStatusEnum.CG.getCode());
                    }else{
                        result.setResult(false);
                        result.setResultCode(ResultStatusEnum.SB.getCode());
                    }
        } catch (Exception e) {
            LoggerHelper.error(logger, e, ResourceUtils.getMessage("UPLOUD_EXPORT_LIC_FILE_EXCEPTION="));
        }
        return  result;
    }

    public boolean deleteLogByEnterpriseId(String enterpriseId){
        return newLicLogService.deleteLogByEnterpriseId(enterpriseId);
    }









    public boolean getAddEnterprise(NewEnterprise newEnterprise,String userId){
        return newEnterpriseService.getAddEnterprise(newEnterprise,userId);
    }

    public boolean queryEnterpriseByName(String enterpriseName){
        return newEnterpriseService.queryEnterpriseByName(enterpriseName);
    }

    public boolean getDeleteEnterpriseById(String id){
        boolean flag = false;
        boolean blag =  newEnterpriseService.getDeleteEnterprise(id);
        if(blag){
            flag = newEnterpriseRegistService.getDeleteNewEnterpriseRegist(id);
        }
        return flag;
    }

    public List<NewLicLog> queryLicLogAll(String enterpriseId){
        return newLicLogService.queryLicLogAll(enterpriseId);
    }




    public List<Map<String,Object>> queryEnterpriseListRegistLicAll(String fkEnterpriseId){
        return genterpriseLicListService.queryEnterpriseListRegistLicAll(fkEnterpriseId);
    }

    public Map<String,Object> queryGenterpriseLicListById(String id){
        return genterpriseLicListService.queryGenterpriseLicListById(id);
    }

    public NewEnterpriseRegistService getNewEnterpriseRegistService() {
        return newEnterpriseRegistService;
    }

    public void setNewEnterpriseRegistService(NewEnterpriseRegistService newEnterpriseRegistService) {
        this.newEnterpriseRegistService = newEnterpriseRegistService;
    }

    public NewEnterpriseService getNewEnterpriseService() {
        return newEnterpriseService;
    }

    public void setNewEnterpriseService(NewEnterpriseService newEnterpriseService) {
        this.newEnterpriseService = newEnterpriseService;
    }

    public GenterpriseLicListService getGenterpriseLicListService() {
        return genterpriseLicListService;
    }

    public void setGenterpriseLicListService(GenterpriseLicListService genterpriseLicListService) {
        this.genterpriseLicListService = genterpriseLicListService;
    }

    public NewLicLogService getNewLicLogService() {
        return newLicLogService;
    }

    public void setNewLicLogService(NewLicLogService newLicLogService) {
        this.newLicLogService = newLicLogService;
    }

    public LicBase getLicBase() {
        return licBase;
    }

    public void setLicBase(LicBase licBase) {
        this.licBase = licBase;
    }
}
